package com.app.dao.user.impl;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.app.beans.User;
import com.app.dao.impl.JdbcTemplateBaseDao;
import com.app.dao.user.UserDao;
import com.app.util.Tools;

@Repository
public class UserDaoImpl extends JdbcTemplateBaseDao implements UserDao<User> {

	@Override
	public boolean addUser(User u) {
		int flag = this.jdbcTemplate.update(
				"insert into user(name,password,email) values (?, ?, ?)",
		        u.getUsername(), u.getPassword(),u.getEmail());
		return flag>0;
	}

	@Override
	public boolean deleteUser(User u) {
		int flag = this.jdbcTemplate.update("delete from user where id = ?",u.getId());
		return flag>0;
	}

	@Override
	public User findUser(int id) {
		User user = this.jdbcTemplate.queryForObject(
	       "select id,name,password,email from user where id = ?",
	       new Object[]{id},
	       new RowMapper<User>() {
	            public User mapRow(ResultSet rs, int rowNum) throws SQLException {
	            	User user = new User();
	            	user.setId(Tools.toInt(rs.getInt("id")));
	            	user.setUsername(Tools.toStr(rs.getString("name")));
	            	user.setPassword(Tools.toStr(rs.getString("password")));
	            	user.setEmail(Tools.toStr(rs.getString("email")));
	                return user;
	            }
        });
		return user;
	}

	@Override
	public boolean updateUser(User u) {
		int flag = this.jdbcTemplate.update("update set name=?,password=?,email=? where id = ?",
				u.getUsername(),u.getPassword(),u.getEmail(),u.getId());
		return flag>0;
	}

}
